package com.iwhalecloud.bss.kite.cucc.service.batch;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.dto.cust.CustDTO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.TransactionUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegionQry;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAccept;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetail;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.batch.KiteBatchAcceptDetailMapper;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.batch.KiteBatchAcceptMapper;
import com.iwhalecloud.bss.kite.cucc.service.batch.attr.BatchAttrUtil;
import com.iwhalecloud.bss.kite.cucc.service.batch.enums.BatchAcceptStatusEnum;
import com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.StatusConst;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProdAttrCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferDetail;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.ProdAttr;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.bo.OrgInfo;
import com.ztesoft.bss.common.bo.StaffInfo;
import com.ztesoft.bss.common.bo.UserInfo;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

import tk.mybatis.mapper.entity.Example;

/**
 * @author lyx
 * @version V1.0
 * @Description:
 * @date 2021/6/1
 * @Package com.iwhalecloud.bss.kite.cucc.service.batch
 */
public class BatchAcceptUtil {

    public static List<Map<String, Object>> packageTmpAttr(String goodsSku, List<List<String>> datas) {
        Offer offer = OfferCache.get(goodsSku);
        List<String> newList = getTmpAttr(datas, offer.getCateId());
        if (KiteListUtils.isEmpty(newList)) {
            BssException.throwOut("", "", "导入的数据为空，请检查");
        }

        List<OfferDetail> offerDetails = offer.listOfferDetails();
        List<ProdAttr> prodAttrs = new ArrayList<>();
        for (OfferDetail offerDetail : offerDetails) {
            String prodId = offerDetail.getObjId();
            prodAttrs = ProdAttrCache.get(prodId);
            break;
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (String cname : newList) {
            Map<String, Object> map = new HashMap<>();
            cname = cname.trim().replace("\n", "");
            String finalCname = cname.trim().replace("*", "");
            ProdAttr prodAttr = prodAttrs.stream()
                .filter(prodAttr1 -> KiteStringUtils.equals(prodAttr1.getCname(), finalCname)
                    || KiteStringUtils.contains(finalCname, "省市区")
                    && KiteStringUtils.equals(prodAttr1.getCname(), finalCname.replace("省市区", "省")))
                .findFirst().orElse(null);

            Assert.notNull(prodAttr, cname + "不存在");
            map.put("cname", cname);
            map.put("fieldName", prodAttr.getFieldName());
            resultList.add(map);

        }
        return resultList;
    }

    public static List<String> getTmpAttr(List<List<String>> datas, String cateId) {
        List<String> newList = new ArrayList<>();
        if (KiteListUtils.isNotEmpty(datas)) {
            List<String> firstRow = datas.get(0);
            List<String> secondRow = datas.size() < 2 ? Lists.newArrayList() : datas.get(1);
            for (int i = 0; i < firstRow.size(); i++) {
                String cellValue = firstRow.get(i);
                if (i + 1 != firstRow.size()) {
                    String nextCellValue = firstRow.get(i + 1);
                    // 如果第一行与第二行数量一直，则认为只有一行，取第一行
                    if (!isTwoTitile(cateId) || !KiteStringUtils.isEmpty(cellValue)
                        && !KiteStringUtils.isEmpty(nextCellValue) && KiteStringUtils.isEmpty(secondRow.get(i))) {
                        newList.add(cellValue);
                    }
                    else {
                        if (i < secondRow.size() && KiteStringUtils.isNotEmpty(secondRow.get(i))) {
                            newList.add(secondRow.get(i));
                        }
                        else {
                            newList.add(cellValue);
                        }
                    }
                }
                else {
                    if (isTwoTitile(cateId) && secondRow.size() > i
                        && KiteStringUtils.isNotEmpty(secondRow.get(i))) {
                        newList.add(secondRow.get(i));
                    }
                    else {
                        newList.add(cellValue);
                    }
                }
            }
        }
        newList = newList.stream().filter(s -> !KiteStringUtils.isEmpty(s)).collect(Collectors.toList());
        return newList;
    }

    public static void delDetailResult(KiteBatchAcceptDetail detail, String message, String status) {
        detail.setCheckResult(message);
//        detail.setDealResult(message);
        detail.setCheckStatus(status);
//        detail.setStatusCd(status);
    }


    public static Runnable wrapLoginInfo(LoginInfo loginInfo, Runnable runnable) {
        return () -> {
            ContextUtil.setLoginInfo2LoginInfoThreadLocal(loginInfo);
            try {
                runnable.run();
            }
            finally {
                ContextUtil.removeThreadLocal();
            }
        };
    }

    public static void wrapLoginInfoNotResult(LoginInfo loginInfo, Runnable runnable) {
        ContextUtil.setLoginInfo2LoginInfoThreadLocal(loginInfo);
        try {
            runnable.run();
        }
        finally {
            ContextUtil.removeThreadLocal();
        }
    }

    public static LoginInfo getLoginInfo(KiteBatchAcceptDetailDTO kiteBatchAccept) {
        LoginInfo loginInfo = new LoginInfo();
        Long userId = kiteBatchAccept.getCreateStaff();
        String orgId = kiteBatchAccept.getCreateOrgId();
        String lanId = kiteBatchAccept.getLanId();
        String postProvinceNbr = kiteBatchAccept.getProvinceId();
        String staffCode = kiteBatchAccept.getCreateStaffCode();
        String regionId = kiteBatchAccept.getRegionId();
        Long staffId = kiteBatchAccept.getCreateStaff();

        UserInfo userInfo = new UserInfo();
        userInfo.setUserCode(staffCode);
        userInfo.setUserId(userId);
        userInfo.setPostLanId(lanId);
        userInfo.setPostProvinceNbr(postProvinceNbr);
        userInfo.setPostRegionId(Long.valueOf(regionId));
        Map<String, Object> extParams = new HashMap<>();
        extParams.put("account", kiteBatchAccept.getJkStaffCode());
        extParams.put("accountId", kiteBatchAccept.getJkStaffId());
        extParams.put("KITE_SCENEINST_CARTID", kiteBatchAccept.getCartId());
        userInfo.setExtParams(extParams);

        OrgInfo orgInfo = new OrgInfo();
        orgInfo.setOrgId(Long.valueOf(orgId));
        orgInfo.setOrgName(kiteBatchAccept.getCreateOrgName());
        StaffInfo staffInfo = new StaffInfo();
        staffInfo.setStaffCode(staffCode);
        staffInfo.setStaffId(staffId);

        loginInfo.setUserInfo(userInfo);
        loginInfo.setOrgInfo(orgInfo);
        loginInfo.setStaffInfo(staffInfo);
        return loginInfo;
    }

    /**
     * 创建12位随机数：时分秒+6位随机数
     * @return
     */
    public static String createRandom() {
        String dateTime = KiteDateUtils.getDateTime();
        String time = dateTime.substring(8);
        SecureRandom random = new SecureRandom();
        int num = random.nextInt(1000000);
        return time + String.format("%04d", num);
    }


    public static List<KiteBatchAcceptDetailDTO> getBatchAcceptDetails(List<String> importTypes) {
        Example batchExample = Example.builder(KiteBatchAccept.class).selectDistinct("batchId").build();
        batchExample.createCriteria().andEqualTo("statusCd", BatchAcceptStatusEnum.STATUS_CD_1400.getStatusCd())
            .andIn("importType", importTypes);
        List<KiteBatchAccept> batchAccepts = SpringUtil.getBean(KiteBatchAcceptMapper.class).selectByExample(batchExample);
        List<String> batchIds = batchAccepts.stream().map(kiteBatchAccept -> kiteBatchAccept.getBatchId().toString())
            .collect(Collectors.toList());
        if (KiteListUtils.isEmpty(batchIds)) {
            return Lists.newArrayList();
        }
        AtomicReference<String> curBatchId = new AtomicReference<>("");
        AtomicReference<String> random = new AtomicReference<>("");
        AtomicReference<List<KiteBatchAcceptDetailDTO>> executeList = new AtomicReference<>(null);
        String num = DcSystemParamCache.getDcParamVal("BATCH_ACCEPT_JOB_NUM");
        if (KiteStringUtils.isEmpty(num)) {
            num = "200";
        }
        KiteBatchAcceptDetailMapper kiteBatchAcceptDetailMapper = SpringUtil.getBean(KiteBatchAcceptDetailMapper.class);
        // 找出要处理的批次
        for (String batchId : batchIds) {
            Integer detailCount = kiteBatchAcceptDetailMapper
                .listCommitBatchDetailCount(Long.valueOf(batchId), BatchAcceptStatusEnum.CHECK_STATUS_1000.getStatusCd(),
                    StatusConst.NOT_STATUSCD);
            if (detailCount <= 0) {
                continue;
            }
            // 拿到批数据的新的随机数，并且更新到批数据中
            // 取数据时要控制事务，取完的数据不允许其它程序再取了
            String tempRandom = BatchAcceptUtil.createRandom();
            try {
                String finalNum = num;
                TransactionUtils.executeNew(() -> kiteBatchAcceptDetailMapper.updateRandom(tempRandom, batchId,
                    Integer.parseInt(finalNum), BatchAcceptStatusEnum.CHECK_STATUS_1000.getStatusCd()));
            }
            catch (Exception e) {
//                e.printStackTrace();
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("更新随机数失败");
            }
            executeList.set(kiteBatchAcceptDetailMapper.listExecuteDetails(batchId, tempRandom));
            //拿到需要处理的数据就中止循环
            if (!KiteListUtils.isEmpty(executeList.get())) {
                random.set(tempRandom);
                curBatchId.set(batchId);
                break;
            }
        }
        return executeList.get();
    }

    public static CustDTO transToCustDTO(CuccContextCustDTO cuccCustInfoDTO) {
        CustDTO dto = new CustDTO();
        if (Objects.nonNull(cuccCustInfoDTO)) {
            KiteBeanUtils.copyProperties(cuccCustInfoDTO, dto);

            //dto.setProvinceCode(cuccCustInfoDTO.getProvinceCode());
            dto.setLanId(cuccCustInfoDTO.getEparchyCode());
            dto.setRegionId(cuccCustInfoDTO.getRegionId());
            dto.setCustType(cuccCustInfoDTO.getCustClassType());
            dto.setCertiType(cuccCustInfoDTO.getCertiTypeCode());
            dto.setCertiNumber(cuccCustInfoDTO.getCertiCode());
            //dto.setBbssCustId(cuccCustInfoDTO.getBbssCustId());
            //dto.setCbssId(cuccCustInfoDTO.getCustId());
        }
        return dto;
    }

    public static boolean isTwoTitile(String cateId) {
        return !KiteStringUtils.contains(DcSystemParamCache.getDcParamVal("BATCH_CONFIG_SINGLE_TITILE"), cateId);
    }

    /**
     * 判断是否批量受理重提、追单环节
     * @param sceneInstId
     * @return
     */
    public static boolean isBatchNode(String sceneInstId) {
        String preTaskCode = SpringUtil.getBean(IQuerySceneInstService.class).getExtParameterValue(sceneInstId, "preTaskCode");
        return KiteStringUtils.equalsAny(preTaskCode, "batchOrderAudit", "batchOrderChase");
    }

    public static Map<String, String> delBatchNodeLog(String attrJosn) {
        Map<String, String> attrMap = JSONObject.parseObject(attrJosn, Map.class);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("业务号码", KiteMapUtils.getString(attrMap, "serialNumber"));
        resultMap.put("订单编码", KiteMapUtils.getString(attrMap, "orderId"));
        resultMap.put("工单id", KiteMapUtils.getString(attrMap, "flowId"));
        resultMap.put("订单环节", KiteMapUtils.getString(attrMap, "nodeCode"));
        resultMap.put("任务名称", KiteMapUtils.getString(attrMap, "taskName"));
        resultMap.put("商品名称", KiteMapUtils.getString(attrMap, "goodsName"));
        String provinceCode = KiteMapUtils.getString(attrMap, "provinceCode");
        String cityCode = KiteMapUtils.getString(attrMap, "cityCode");
        String districtCode = KiteMapUtils.getString(attrMap, "districtCode");
        IUnicomRegionService unicomRegionService = SpringUtil.getBean(IUnicomRegionService.class);
        // 省
        List<UnicomRegion> provinceList = unicomRegionService.subRegionFromPlatform(new UnicomRegionQry());
        String provinceName =
            provinceList.stream().filter(p -> KiteStringUtils.equals(p.getRegionCode(), provinceCode)).findFirst()
                .map(UnicomRegion::getRegionName).orElse("");
        // 市
        List<UnicomRegion> cityList =
            unicomRegionService.subRegionFromPlatform(new UnicomRegionQry(provinceCode, "20"));
        String cityName = cityList.stream().filter(p -> KiteStringUtils.equals(p.getRegionCode(), cityCode))
            .findFirst().map(UnicomRegion::getRegionName).orElse("");
        // 区
        List<UnicomRegion> areaList =
            unicomRegionService.subRegionFromPlatform(new UnicomRegionQry(cityCode, "30"));
        String areaName = areaList.stream().filter(p -> KiteStringUtils.equals(p.getRegionCode(), districtCode))
            .findFirst().map(UnicomRegion::getRegionName).orElse("");
        String regionValDesc = String.join(SymbolConsts.HYPHEN, provinceName, cityName, areaName);
        resultMap.put("用户归属", regionValDesc);
        resultMap.put("创建时间", KiteMapUtils.getString(attrMap, "creatTime"));
        return resultMap;
    }

    public static void delAddress(List<KiteAttr> attrList, String provinceFieldName, String cityFieldName,
                                  String districtFieldName) {
        KiteAttr province = attrList.stream()
            .filter(commonAttrVO -> KiteStringUtils.equals(commonAttrVO.getFieldName(), provinceFieldName)).findFirst()
            .orElse(null);
        if (Objects.nonNull(province) && KiteStringUtils.isNotEmpty(province.getValue())) {
            String[] fields = province.getValue().split(SymbolConsts.SLASH);
            if (fields.length < 3) {
                return;
            }
            province.setValue(fields[0]);
            // 市
            KiteAttr city = attrList.stream()
                .filter(commonAttrVO -> KiteStringUtils.equals(commonAttrVO.getFieldName(), cityFieldName)).findFirst()
                .orElse(null);
            if (Objects.nonNull(city)) {
                city.setValue(fields[1]);
            }
            else {
                KiteAttr kiteAttr = new KiteAttr();
                kiteAttr.setValue(fields[1]);
                kiteAttr.setFieldName(cityFieldName);
                attrList.add(kiteAttr);
            }
            // 区
            KiteAttr district = attrList.stream()
                .filter(commonAttrVO -> KiteStringUtils.equals(commonAttrVO.getFieldName(), districtFieldName))
                .findFirst().orElse(null);
            if (Objects.nonNull(district)) {
                district.setValue(fields[2]);
            }
            else {
                KiteAttr kiteAttr = new KiteAttr();
                kiteAttr.setValue(fields[2]);
                kiteAttr.setFieldName(districtFieldName);
                attrList.add(kiteAttr);
            }
        }
    }

    public static void delAddressMvCity(List<KiteAttr> attrList, String firstAddrFieldName, String provinceFieldName,
        String cityFieldName, String districtFieldName) {
        KiteAttr province = attrList.stream()
            .filter(commonAttrVO -> KiteStringUtils.equals(commonAttrVO.getFieldName(), provinceFieldName)).findFirst()
            .orElse(null);
        KiteAttr addrAttr = attrList.stream()
            .filter(commonAttrVO -> KiteStringUtils.equals(commonAttrVO.getFieldName(), firstAddrFieldName)).findFirst()
            .orElse(null);
        if ( Objects.nonNull(addrAttr) && KiteStringUtils.isNotEmpty(addrAttr.getValue())) {
            String[] fields = addrAttr.getValue().split(SymbolConsts.SLASH);
            if (fields.length < 3) {
                return;
            }
            if (Objects.nonNull(province)) {
                province.setValue(fields[0]);
            }
            else {
                KiteAttr kiteAttr = new KiteAttr();
                kiteAttr.setValue(fields[0]);
                kiteAttr.setFieldName(provinceFieldName);
                attrList.add(kiteAttr);
            }

            // 市
            KiteAttr city = attrList.stream()
                .filter(commonAttrVO -> KiteStringUtils.equals(commonAttrVO.getFieldName(), cityFieldName)).findFirst()
                .orElse(null);
            if (Objects.nonNull(city)) {
                city.setValue(fields[1]);
            }
            else {
                KiteAttr kiteAttr = new KiteAttr();
                kiteAttr.setValue(fields[1]);
                kiteAttr.setFieldName(cityFieldName);
                attrList.add(kiteAttr);
            }
            // 区
            KiteAttr district = attrList.stream()
                .filter(commonAttrVO -> KiteStringUtils.equals(commonAttrVO.getFieldName(), districtFieldName))
                .findFirst().orElse(null);
            if (Objects.nonNull(district)) {
                district.setValue(fields[2]);
            }
            else {
                KiteAttr kiteAttr = new KiteAttr();
                kiteAttr.setValue(fields[2]);
                kiteAttr.setFieldName(districtFieldName);
                attrList.add(kiteAttr);
            }
        }
    }


    public static void delInstAddress(KiteProdInst prodInst, List<KiteAttr> attrList, String firstAddrFieldName,
        String lastAddrFieldName, String provinceFieldName) {
        KiteAttr instFirstAddr = prodInst.getAttr(firstAddrFieldName);
        KiteAttr firstAddr = attrList.stream()
            .filter(attr -> KiteStringUtils.equals(firstAddrFieldName, attr.getFieldName())).findFirst().orElse(null);
        KiteAttr instLastAddr = prodInst.getAttr(lastAddrFieldName);
        KiteAttr province = attrList.stream()
            .filter(attr -> KiteStringUtils.equals(provinceFieldName, attr.getFieldName())).findFirst().orElse(null);

        if (Objects.isNull(firstAddr) || Objects.isNull(instLastAddr) || Objects.isNull(province)) {
            return;
        }

        // fisrtAddr 实例存的是省市区，但是页面展示的是详细装机地址，需要转换
        String area = instFirstAddr.getValueDesc();
        firstAddr.setValue(instLastAddr.getValueDesc());
        // 将fisrtAddr存的省市区存入province
        if (KiteStringUtils.isNotEmpty(area)) {
            String[] valueArray = area.split(",");
            province.setValue(KiteStringUtils.concatArrayWithSymbol(valueArray, "/"));
        }
    }

    public static void isBatchAcceptGoods(Offer offer) {
        String batchAcceptGoods = DcSystemParamCache.getDcParamVal("BATCH_ACCEPT_GOODS");
        // 2004026光纤、2004017MV、2004029互联网、SDH:2004023、2004022、2004021、2004020、以太网：2004034、2004033、2004032、2004031
        if (Objects.isNull(offer) || KiteStringUtils.isBlank(batchAcceptGoods) || !KiteStringUtils
            .equalsAny(offer.getAttrValue("cateId"), batchAcceptGoods.split(SymbolConsts.COMMA))) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("此商品不允许批量受理，如需要，请联系管理员修改配置");
        }
    }

    public static void delAddressRule(Map<String, Object> attrMap, String provinceCode, String provinceFieldName, String cityFieldName,
                                  String districtFieldName, String firstAddress, String addressFieldName) {
        KiteAttr provinceAttr = (KiteAttr) attrMap.get(provinceFieldName);
        if (Objects.nonNull(provinceAttr) && KiteStringUtils.isNotEmpty(provinceAttr.getValue())) {
            String[] fields = provinceAttr.getValue().split(SymbolConsts.SLASH);
            if (fields.length < 3) {
                return;
            }
            provinceAttr.setValue(provinceCode);
            provinceAttr.setValueDesc(fields[0]);
            // 市
            String cityName = fields[1];
            String cityCode = null;
            KiteAttr cityAttr = (KiteAttr) attrMap.get(cityFieldName);
            if (Objects.nonNull(cityAttr)) {
                List<UnicomRegion> cities = SpringUtil.getBean(IUnicomRegionService.class)
                    .subRegionFromPlatform(new UnicomRegionQry(provinceCode, "20"));
                UnicomRegion city = Objects.requireNonNull(cities).stream()
                    .filter(unicomRegion -> KiteStringUtils.isEqual(unicomRegion.getRegionName(), cityName)).findFirst()
                    .orElse(new UnicomRegion());
                cityCode = city.getRegionCode();
                cityAttr.setValue(city.getRegionCode());
                cityAttr.setValueDesc(city.getRegionName());
            }

            // 区
            KiteAttr districtAttr = (KiteAttr) attrMap.get(districtFieldName);
            String districtName = fields[2];
            String districtCode = null;
            if (Objects.nonNull(districtAttr) && KiteStringUtils.isNotEmpty(cityCode)) {
                List<UnicomRegion> districts = SpringUtil.getBean(IUnicomRegionService.class)
                    .subRegionFromPlatform(new UnicomRegionQry(cityCode, "30"));
                UnicomRegion district = Objects.requireNonNull(districts).stream()
                    .filter(unicomRegion -> BatchAttrUtil.matchDistrict(districtName, unicomRegion.getRegionName()))
                    .findFirst().orElse(new UnicomRegion());
                districtCode = district.getRegionCode();
                districtAttr.setValue(districtCode);
                districtAttr.setValueDesc(district.getRegionName());
            }

            // 装机地址省市区
            KiteAttr firstAddressAttr = (KiteAttr) attrMap.get(firstAddress);
            String addressValue = null;
            String firstAddr = KiteStringUtils.joinWith(SymbolConsts.COMMA, provinceCode, cityCode, districtCode);
            if (Objects.nonNull(firstAddressAttr)) {
                addressValue = firstAddressAttr.getValue();
                firstAddressAttr.setValue(firstAddr);
                firstAddressAttr.setValueDesc(firstAddr);
            }
            // 装机地址
            if (KiteStringUtils.isNotEmpty(addressFieldName)) {
                KiteAttr addressAttr = (KiteAttr) attrMap.get(addressFieldName);
                if (Objects.nonNull(firstAddressAttr)) {
                    addressAttr.setValue(addressValue);
                }
            }
        }
    }

    public static void delAddressRuleMVCity(Map<String, Object> attrMap, String provinceCode, String provinceFieldName, String cityFieldName,
                                      String districtFieldName, String firstAddress) {
        KiteAttr provinceAttr = (KiteAttr) attrMap.get(provinceFieldName);
        KiteAttr firstAddressAttr = (KiteAttr) attrMap.get(firstAddress);
        if (Objects.nonNull(provinceAttr) && Objects.nonNull(firstAddressAttr)
            && KiteStringUtils.isNotEmpty(firstAddressAttr.getValue())) {
            String[] fields = firstAddressAttr.getValue().split(SymbolConsts.SLASH);
            if (fields.length < 3) {
                return;
            }
            provinceAttr.setValue(provinceCode);
            provinceAttr.setValueDesc(fields[0]);
            // 市
            String cityName = fields[1];
            String cityCode = null;
            KiteAttr cityAttr = (KiteAttr) attrMap.get(cityFieldName);
            if (Objects.nonNull(cityAttr)) {
                List<UnicomRegion> cities = SpringUtil.getBean(IUnicomRegionService.class)
                    .subRegionFromPlatform(new UnicomRegionQry(provinceCode, "20"));
                UnicomRegion city = Objects.requireNonNull(cities).stream()
                    .filter(unicomRegion -> KiteStringUtils.isEqual(unicomRegion.getRegionName(), cityName)).findFirst()
                    .orElse(new UnicomRegion());
                cityCode = city.getRegionCode();
                cityAttr.setValue(city.getRegionCode());
                cityAttr.setValueDesc(city.getRegionName());
            }

            // 区
            KiteAttr districtAttr = (KiteAttr) attrMap.get(districtFieldName);
            String districtName = fields[2];
            String districtCode = null;
            if (Objects.nonNull(districtAttr) && KiteStringUtils.isNotEmpty(cityCode)) {
                List<UnicomRegion> districts = SpringUtil.getBean(IUnicomRegionService.class)
                    .subRegionFromPlatform(new UnicomRegionQry(cityCode, "30"));
                UnicomRegion district = Objects.requireNonNull(districts).stream()
                    .filter(unicomRegion -> BatchAttrUtil.matchDistrict(districtName, unicomRegion.getRegionName()))
                    .findFirst().orElse(new UnicomRegion());
                districtCode = district.getRegionCode();
                districtAttr.setValue(districtCode);
                districtAttr.setValueDesc(district.getRegionName());
            }

            // 省市区
            String firstAddr = KiteStringUtils.joinWith(SymbolConsts.COMMA, provinceCode, cityCode, districtCode);
            firstAddressAttr.setValue(firstAddr);

        }
    }

    public static Boolean isBatchStartRent(String sceneInstId) {
        return KiteStringUtils.equals(
            SpringUtil.getBean(IQuerySceneInstService.class).getExtParameterValue(sceneInstId, "preTaskCode"),
            "batchOrderStartRent");
    }

    public static Boolean isBatchSign(String sceneInstId) {
        return KiteStringUtils.equals(
            SpringUtil.getBean(IQuerySceneInstService.class).getExtParameterValue(sceneInstId, "preTaskCode"),
            "batchSIGN");
    }

    /**
     * 判断批量签订重提是否置灰（返回true置灰）
     * 1.根据子单编号查批次明细表，不存在则认为不是重提，不需要置灰
     * 2.根据子单编号查批次明细表，存在则认为是重提。
     * 比较 orderSize 与 批次表当前批次的数量，如果一致，则认为是全部失败，不需要置灰。否则置灰
     * 如果是多次重提的场景，找出所有有这个子单的批次，判断如果某个批次的总数>orderSize，则认为是部分成功，置灰
     * @param orderId 子单订单编号
     * @param orderSize 工单合并查询的子单数量
     * @return Boolean
     */
    public static boolean isBatchNodeReset(String orderId, int orderSize, String preTaskCode) {
//        long startTime = System.currentTimeMillis();
//        KiteBatchAcceptDetailMapper kiteBatchAcceptDetailMapper = SpringUtil.getBean(KiteBatchAcceptDetailMapper.class);
//        Example example = new Example(KiteBatchAcceptDetail.class);
//        example.createCriteria().andEqualTo("extOrderId", orderId);
//        example.setOrderByClause("status_date desc");
//        List<KiteBatchAcceptDetail> details = kiteBatchAcceptDetailMapper.selectByExample(example);
//        if (KiteListUtils.isEmpty(details)) {
//            return Boolean.TRUE;
//        }
//        int batchCount = kiteBatchAcceptDetailMapper.selectCount(new KiteBatchAcceptDetail().setBatchId(details.get(0).getBatchId()));
//        // 如果当前环节的数量，与批次表数量一致，则认为是全部失败
//        if (batchCount == orderSize) {
//            return Boolean.FALSE;
//        }
//        long enTime = System.currentTimeMillis();
//        System.out.println("查数据库耗时：" + (enTime - startTime));

        String importType = "7100";
        if (KiteStringUtils.equals(preTaskCode, "batchOrderStartRent")) {
            importType = "7200";
        }
        KiteBatchAcceptMapper kiteBatchAcceptMapper = SpringUtil.getBean(KiteBatchAcceptMapper.class);
        Example example = new Example(KiteBatchAccept.class);
        example.createCriteria().andEqualTo("createStaff", ContextUtil.getLoginInfo().getStaffInfo().getStaffId())
            .andEqualTo("importType", importType).andEqualTo("statusCd", "1400");
        example.setOrderByClause("create_date desc");
        List<KiteBatchAccept> batchAccepts = kiteBatchAcceptMapper.selectByExample(example);
        KiteBatchAcceptDetailMapper kiteBatchAcceptDetailMapper = SpringUtil.getBean(KiteBatchAcceptDetailMapper.class);
        if (KiteListUtils.isEmpty(batchAccepts)) {
            return Boolean.TRUE;
        }
        for (KiteBatchAccept batchAccept : batchAccepts) {
            List<KiteBatchAcceptDetail> details =
                kiteBatchAcceptDetailMapper.select(new KiteBatchAcceptDetail().setBatchId(batchAccept.getBatchId()));
            if (KiteListUtils.isEmpty(details)) {
                continue;
            }
            if (details.stream().anyMatch(detail -> KiteStringUtils.equals(detail.getExtOrderId(), orderId))) {
                if (details.size() > orderSize) {
                    return Boolean.FALSE;
                }
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 批量签订重提是否可以编辑
     * @param sceneInstId
     * @return
     */
    public static boolean batchNodeResetIsEdit(String sceneInstId) {
        String isEdit = SpringUtil.getBean(IQuerySceneInstService.class).getExtParameterValue(sceneInstId, "batchNodeResetIsEdit");
        return KiteStringUtils.equals(isEdit, "F");
    }

    public static List<List<KiteBatchAcceptDetailDTO>> partition(List<KiteBatchAcceptDetailDTO> list, int size) {
        List<List<KiteBatchAcceptDetailDTO>> listArr = new ArrayList<>();
        int arrSize = list.size() % size == 0 ? list.size() / size : list.size() / size + 1;
        for (int i = 0; i < arrSize; i++) {
            List<KiteBatchAcceptDetailDTO> sub = new ArrayList<>();
            for (int j = i * size; j <= size * (i + 1) - 1; j++) {
                if (j <= list.size() - 1) {
                    sub.add(list.get(j));
                }
            }
            listArr.add(sub);
        }
        return listArr;
    }

}
